<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert title="添加商品信息" type="info" center :closable='false' show-icon>
      </el-alert>
      <!-- 头部步骤条 -->
      <!-- 加0是拼接，减0转换成number类型，加号是字符串的隐式类型转换方式 -->
      <el-steps :active="active - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 内容主体区域 -->
      <el-form label-width="80px" :model="addForm" :rules="addFormRule" label-position='top' ref="addFormRef"
        @close="resetAddForm('addFormRef')">
        <el-tabs tab-position="left" v-model="active" style="margin-top: 15px;" :before-leave="tabLeave">
          <el-tab-pane label="基本信息" name='0'>
            <el-form-item prop="goods_name" label="商品名称">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item prop="goods_price" label="商品价格">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item prop="goods_weight" label="商品重量">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item prop="goods_number" label="商品数量">
              <el-input-number v-model="addForm.goods_number" :min="1" label="商品数量"></el-input-number>
            </el-form-item>
            <el-form-item prop="goods_cat" label="商品分类">
              <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="prop" clearable
                @change="selectChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name='1'>
            <el-form-item :label="item.attr_name" v-for="(item,i1) in attrList" :key="i1">
              <el-checkbox-group v-model="item.new_vals">
                <el-checkbox v-for="(item2,i2) in item.new_vals" :key="i2" :label="item2" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name='2'>
            <el-form-item v-for="(item,index) in onlyList" :key="index" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name='3'>
            <el-upload class="upload-demo" action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview" :on-remove="handleRemove" :headers="headersObj" :on-success="handleSuccess"
              :file="addForm.pics" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name='4'>
            <!-- 富文本编辑器 -->
            <quill-editor ref="myQuillEditor" v-model="addForm.goods_introduce"/>
            <!-- 添加商品的按钮 -->
            <el-button type="primary" style="margin-top: 20px; float:right;" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="picPreview" width="50%">
      <img :src="previewPath" alt="" class="preImg">
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      active: 0,
      //   获取商品分类数据
      cateList: [],
      //   获取动态参数列表
      attrList: [],
      onlyList: [],

      // 指定级联选择器的配置对象
      prop: {
        children: 'children',
        label: 'cat_name',
        value: 'cat_id',
        expandTrigger: 'hover'
      },
      // 上传头部请求
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      //   添加商品的表单数据对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: '',
        // 存放图片
        pics: [],
        // 商品的详情描述
        goods_introduce: '',
        attrs: []
      },
      addFormRule: {
        goods_name: [{
          required: true,
          message: '请输入商品名称',
          trigger: 'blur'
        }],
        goods_price: [{
          required: true,
          message: '请输入商品价格',
          trigger: 'blur'
        }],
        goods_weight: [{
          required: true,
          message: '请输入商品重量',
          trigger: 'blur'
        }],
        goods_number: [{
          required: true,
          message: '请输入商品数量',
          trigger: 'blur'
        }],
        goods_cat: [{
          required: true,
          message: '请选择商品分类',
          trigger: 'blur'
        }]
      },
      // 图片的预览路径
      previewPath: '',
      picPreview: false
    }
  },
  created () {
    this.getCateList()
  },
  computed: {
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  },
  methods: {
    async commonGetAttr (type, arr) {
      const {
        data: res
      } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: type
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败！')
      }
      res.data.forEach(item => {
        item.new_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
      })
      if (type === 'only') {
        this.onlyList = res.data
      } else if (type === 'many') {
        this.attrList = res.data
      }
    },
    tabLeave (activeName, oldActiveName) {
      // 如果处于第一个标签
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类！')
        return false
      }
      //  动态参数列表的获取
      if (activeName === '1') {
        this.commonGetAttr('many')
      } else if (activeName === '2') {
        this.commonGetAttr('only')
        console.log(this.onlyList)
      }
    },
    // 重置表单
    resetAddForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 获取商品分类数据
    async getCateList () {
      const {
        data: res
      } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败!')
      }
      this.cateList = res.data
    },
    // 监听下拉框
    selectChange () {
      if (this.addForm.goods_cat.length !== 3 && this.addForm.goods_cat.length !== 0) {
        this.addForm.goods_cat = []
        return this.$message.error('只能为第三级分类添加商品')
      }
    },
    // 处理移除图片的函数
    handleRemove (file, fileList) {
      const path = file.response.data.tmp_path
      // 方法一：使用splice
      const i = this.addForm.pics.findIndex(x => x.pic === path)
      this.addForm.pics.splice(i, 1)
      // 方法二：使用filter
      // this.addForm.pics = this.addForm.pics.filter(item => item.pic !== path)
      console.log(this.addForm)
    },
    // 处理图片预览效果
    handlePreview (file) {
      this.previewPath = file.response.data.url
      this.picPreview = true
    },
    // 监听图片上传效果
    handleSuccess (response) {
      const picInfo = {
        pic: response.data.tmp_path
      }
      this.addForm.pics.push(picInfo)
    },
    // 添加商品
    addGoods () {
      this.$refs.addFormRef.validate(
        async valid => {
          if (!valid) {
            return this.$message.error('请填写必要的表单项')
          }
          const Form = JSON.parse(JSON.stringify(this.addForm))
          Form.goods_cat = Form.goods_cat.join(',')
          this.attrList.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(' ')
            }
            Form.attrs.push(newInfo)
          })
          this.onlyList.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_vals: item.attr_vals
            }
            Form.attrs.push(newInfo)
          })
          console.log(Form)
          const { data: res } = await this.$http.post('goods', Form)
          if (res.meta.status !== 201) {
            return this.$message.error('添加商品失败！')
          }
          this.$message.success('添加商品成功')
          this.$router.push('/goods')
        }
      )
    }
  }
}

</script>
<style lang="less" scoped>
  .el-steps {
    margin-top: 20px;
  }

  .el-checkbox {
    margin: 0 5px 0 0 !important;
  }

  .preImg {
    width: 100%;
    height: 100%;
  }

</style>
